package cn.ycc1.boot3mq.order.mq;

import cn.ycc1.boot3mq.config.RabbitConstant;
import com.rabbitmq.client.Channel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.converter.SmartMessageConverter;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 张治保
 * date 2022/6/9
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class OrderRabbitListener {
//    private final SmartMessageConverter smartMessageConverter;

    /**
     * 把订单数据刷新到数据库
     */
//    @RabbitListener(queues = OrderQueueNames.ORDER_CREATE_FLUSH_DATA2DB_QUEUE, containerFactory = RabbitConstant.BATCH_LISTENER_CONTAINER_FACTORY, executor = "orderTaskExecutor")
    public void orderCreate(List<Message> messages, Channel channel) throws IOException {
//        createOrderService.saveOrder2DbBatch(
//                messages.stream().
//                        map(message -> (OrderDetailInfoBO) smartMessageConverter.fromMessage(message))
//                        .collect(Collectors.toList())
//        );
        //批量 确认消息
        for (Message message : messages) {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
        }
    }

    /**
     * 支付超时取消订单
     */
    @RabbitListener(queues = OrderQueueNames.ORDER_AUTO_PAID_TIMEOUT_CLOSE_QUEUE)
    public void orderCancelNotPay(String orderNo, Channel channel, Message message) throws IOException {
//        closeOrderService.closeOrderPaidTimeout(orderNo);
        System.out.println(orderNo);
        System.out.println("接收到订单超时关闭消息");
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

    /**
     * 发送对象测试消息确认
     */
    @RabbitListener(queues = OrderQueueNames.OBJECT_QUEUE)
    public void orderSend(Map<String, Object> map, Channel channel, Message message) throws IOException {
        System.out.println(map);
        System.out.println("接收到发送的对象消息" + map);
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

}
